﻿using Furion;
using Furion.Authorization;
using Furion.DatabaseAccessor;
using Furion.DataEncryption;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using JoyAdmin.Core;
using JoyAdmin.Core.Extension;
using JoyAdmin.Core.Model;
using Mapster;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Input;

namespace JoyAdmin.Application
{
    /// <summary>
    /// 角色管理服务
    /// </summary>

    public class RBACService : IDynamicApiController
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IRepository<User> _userRepository;
        private readonly IRepository<Role> _roleRepository;
        private readonly IRepository<UserRole> _userRoleRepository;
        private readonly IRepository<RoleSecurity> _roleSecurityRepository;
        private readonly IRepository<Security> _securityRepository;
        private readonly IRepository<IPLog> _iplogRepository;
        private readonly IAuthorizationManager _authorizationManager;
        private readonly IRepository<Customer> _custRepository;
        private readonly IRepository<TransDevice> _repTranDevice;
        private readonly IRepository<AgreeMent> _agreeRepository;
        private readonly IRepository<AgreementFieldTemplate> _agreefieldRepository;
        private readonly IRepository<EssConfig> _essRepository;
        private readonly IRepository<FileCustomer> _fileRepository;

        private readonly IRepository<device_info, MySqlDbContextLocator> _DeviceNoClassRepository;


        public RBACService(IHttpContextAccessor httpContextAccessor
            , IRepository<User> userRepository
            , IRepository<Role> roleRepository
            , IRepository<UserRole> userRoleRepository
            , IRepository<RoleSecurity> roleSecurityRepository
            , IRepository<Security> securityRepository
            , IRepository<IPLog> iplogRepository
            , IAuthorizationManager authorizationManager
            , IRepository<Customer> custRepository
            , IRepository<TransDevice> repTranDevice
            , IRepository<AgreeMent> agreeRepository
            , IRepository<AgreementFieldTemplate> agreefieldRepository
            , IRepository<EssConfig> essRepository
            , IRepository<FileCustomer> fileRepository
            , IRepository<device_info, MySqlDbContextLocator> DeviceNoClassRepository
            )
        {
            _httpContextAccessor = httpContextAccessor;
            _userRepository = userRepository;
            _roleRepository = roleRepository;
            _userRoleRepository = userRoleRepository;
            _roleSecurityRepository = roleSecurityRepository;
            _securityRepository = securityRepository;
            _iplogRepository = iplogRepository;
            _authorizationManager = authorizationManager;
            _custRepository = custRepository;
            _repTranDevice = repTranDevice;
            _agreeRepository = agreeRepository;
            _agreefieldRepository = agreefieldRepository;
            _essRepository = essRepository;
            _fileRepository = fileRepository;

            _DeviceNoClassRepository = DeviceNoClassRepository;
        }

        /// <summary>
        /// 登录（免授权）
        /// </summary>
        /// <param name="input"></param>
        /// <remarks>管理员：admin/654321；</remarks>
        /// <returns></returns>
        [AllowAnonymous]
        public UserDto Login(LoginInput input)
        {
            // 验证用户名和密码
            var user = _userRepository.FirstOrDefault(u => u.Account.Equals(input.Account)) ?? throw Oops.Oh(ErrorCode.WrongUser).StatusCode(ErrorStatus.ValidationFaild);
            if (!user.Password.Equals(MD5Encryption.Encrypt(input.Password)))
            {
                throw Oops.Oh(ErrorCode.WrongPwd).StatusCode(ErrorStatus.ValidationFaild);
            }
            var output = user.Adapt<UserDto>();

            output.Token = JWTEncryption.Encrypt(new Dictionary<string, object>()
            {

                { ClaimConst.CLAINM_USERID, user.Id },
                { ClaimConst.CLAINM_ACCOUNT,user.Account },
                { ClaimConst.CLAINM_NAME, user.Name },

            });

            //NetInfo netinfo = HttpHelper.getNetInfo();
            //var ipEntity = netinfo.Adapt<IPLog>();
            //ipEntity.UserId = user.Id;
            //ipEntity.UserAccount = user.Account;
            //ipEntity.UserName = user.Name;
            //_iplogRepository.InsertNow(ipEntity);
            // 设置 Swagger 刷新自动授权
            _httpContextAccessor.HttpContext.Response.Headers["access-token"] = output.Token;

            return output;
        }

        /// <summary>
        /// 查看用户信息
        /// </summary>
        public UserDto GetUserInfo()
        {
            // 获取用户Id
            var userId = _authorizationManager.GetUserId();
            var entity = _userRepository
                .Include(u => u.Roles)
                    .ThenInclude(u => u.Securities)
                .Where(u => u.Id == userId).FirstOrDefault();

            UserDto user = entity.Adapt<UserDto>();
            user.Access = new List<string>();
            entity.Roles.SelectMany(r => r.Securities).ToList().ForEach(s =>
            {
                user.Access.Add(s.UniqueCode);
            });
            return user;
        }


        #region 权限管理
        /// <summary>
        /// 权限列表
        /// </summary> 
        public List<SecurityDto> GetAuth()
        {
            return _securityRepository.AsEnumerable().OrderBy(m => m.Sort).Adapt<List<SecurityDto>>();
        }

        /// <summary>
        /// 保存权限
        /// </summary>
        [SecurityDefine("auth")]
        public Task SaveAuth(SecurityDto input)
        {
            if (input.Id == 0)
            {
                var hasData = _securityRepository.Where(m => m.UniqueCode == input.UniqueCode || m.UniqueName == input.UniqueName).FirstOrDefault();
                if (hasData != null)
                {
                    if (hasData.UniqueCode == input.UniqueCode)
                    {
                        throw Oops.Oh(ErrorCode.WrongValidation, "已存在此权限编码").StatusCode(ErrorStatus.ValidationFaild);
                    }
                    else if (hasData.UniqueName == input.UniqueName)
                    {
                        throw Oops.Oh(ErrorCode.WrongValidation, "已存在此权限名称").StatusCode(ErrorStatus.ValidationFaild);
                    }
                }
                return _securityRepository.InsertAsync(input.Adapt<Security>());
            }
            else
            {
                var hasData = _securityRepository.Where(m => m.Id != input.Id && (m.UniqueCode == input.UniqueCode || m.UniqueName == input.UniqueName)).FirstOrDefault();
                if (hasData != null)
                {
                    if (hasData.UniqueCode == input.UniqueCode)
                    {
                        throw Oops.Oh(ErrorCode.WrongValidation, "已存在此权限编码").StatusCode(ErrorStatus.ValidationFaild);
                    }
                    else if (hasData.UniqueName == input.UniqueName)
                    {
                        throw Oops.Oh(ErrorCode.WrongValidation, "已存在此权限名称").StatusCode(ErrorStatus.ValidationFaild);
                    }
                }
                return _securityRepository.UpdateAsync(input.Adapt<Security>());
            }


        }
        /// <summary>
        /// 删除权限
        /// </summary>
        [SecurityDefine("auth")]
        public Task DeleteAuth(long id)
        {
            return _securityRepository.FakeDeleteAsync(id);
        }
        #endregion

        #region 角色管理
        /// <summary>
        /// 角色列表
        /// </summary> 
        public List<RoleDto> GetRole()
        {
            return _roleRepository.AsEnumerable().OrderBy(m => m.Sort).Adapt<List<RoleDto>>();
        }
        /// <summary>
        /// 获取某个角色的权限
        /// </summary>
        [SecurityDefine("role")]
        public List<SecurityDto> GetAuthByRoleId(long id)
        {
            var securities = _roleRepository.Include(u => u.Securities)
              .Where(u => u.Id == id).SelectMany(u => u.Securities);
            return securities.Adapt<List<SecurityDto>>();
        }
        /// <summary>
        /// 保存角色
        /// </summary>
        [SecurityDefine("role")]
        public Task SaveRole(RoleDto input)
        {
            if (input.Id == 0)
            {

                var hasData = _roleRepository.Where(m => m.Name == input.Name).FirstOrDefault();
                if (hasData != null)
                {
                    throw Oops.Oh(ErrorCode.WrongValidation, "已存在此角色名称").StatusCode(ErrorStatus.ValidationFaild);
                }
                return _roleRepository.InsertAsync(input.Adapt<Role>());
            }
            else
            {
                var hasData = _roleRepository.Where(m => m.Name == input.Name && m.Id != input.Id).FirstOrDefault();
                if (hasData != null)
                {
                    throw Oops.Oh(ErrorCode.WrongValidation, "已存在此角色名称").StatusCode(ErrorStatus.ValidationFaild);
                }
                return _roleRepository.UpdateAsync(input.Adapt<Role>());
            }


        }
        /// <summary>
        /// 删除角色
        /// </summary>
        [SecurityDefine("role")]
        public Task DeleteRole(long id)
        {
            return _roleRepository.FakeDeleteAsync(id);
        }


        /// <summary>
        /// 为角色分配权限
        /// </summary>
        [SecurityDefine("role")]
        public Task GiveRoleSecurity(RoleSecurityInput input)
        {
            input.SecurityIds ??= Array.Empty<long>();
            _roleSecurityRepository.Delete(_roleSecurityRepository.Where(u => u.RoleId == input.RoleId).ToList());

            var list = new List<RoleSecurity>();
            foreach (var securityId in input.SecurityIds)
            {
                list.Add(new RoleSecurity { RoleId = input.RoleId, SecurityId = securityId });
            }

            return _roleSecurityRepository.InsertAsync(list);
        }
        #endregion

        #region 员工管理

        /// <summary>
        /// 查询员工
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [SecurityDefine("employee")]
        public PagedList<UserDto> SearchEmployee(UserInput input)
        {
            var search = _userRepository.AsQueryable();

            if (!string.IsNullOrEmpty(input.keyword))
            {
                search = search.Where(m => m.Name.Contains(input.keyword) || m.Account.Contains(input.keyword));
            }
            var users = search.ToPagedList(input.page, input.size).Adapt<PagedList<UserDto>>();
            return users;
        }

        /// <summary>
        /// 保存员工
        /// </summary>
        [SecurityDefine("employee")]
        public Task SaveEmployee(UserDto input)
        {

            if (input.Id <= 0)
            {
                var oldUser = _userRepository.Where(m => m.Account == input.Account).FirstOrDefault();
                if (oldUser != null)
                {
                    throw Oops.Oh(ErrorCode.WrongValidation, "该账号已存在").StatusCode(ErrorStatus.ValidationFaild);
                }

                User user = input.Adapt<User>();
                user.Password = MD5Encryption.Encrypt("123456");//默认密码为123456
                return _userRepository.InsertAsync(user);
            }
            else
            {
                var oldUser = _userRepository.Where(m => m.Account == input.Account && m.Id != input.Id).FirstOrDefault();
                if (oldUser != null)
                {
                    throw Oops.Oh(ErrorCode.WrongValidation, "该账号已存在").StatusCode(ErrorStatus.ValidationFaild);
                }
                User user = input.Adapt<User>();
                return _userRepository.UpdateExcludeAsync(user, new[] { nameof(user.IsDeleted), nameof(user.Password) });
            }


        }
        /// <summary>
        /// 删除员工
        /// </summary>
        [SecurityDefine("employee")]
        public Task DeleteEmployee(long id)
        {
            // 获取用户Id
            var userId = _authorizationManager.GetUserId();
            if (userId == id)
            {
                throw Oops.Oh(ErrorCode.WrongValidation, "不能删除当前账号").StatusCode(ErrorStatus.ValidationFaild);
            }
            return _userRepository.FakeDeleteAsync(id);
        }
        /// <summary>
        /// 获取某个员工的角色
        /// </summary>
        [SecurityDefine("employee")]
        public List<RoleDto> GetRoleByUserId(long id)
        {
            var roles = _userRepository.Include(u => u.Roles)
              .Where(u => u.Id == id).SelectMany(u => u.Roles);
            return roles.Adapt<List<RoleDto>>();
        }
        /// <summary>
        /// 为用户分配角色
        /// </summary>
        [SecurityDefine("employee")]
        public Task GiveUserRole(UserRoleInput input)
        {
            // 获取用户Id

            input.RoleIds ??= Array.Empty<long>();
            _userRoleRepository.Delete(_userRoleRepository.Where(u => u.UserId == input.UserId).ToList());

            var list = new List<UserRole>();
            foreach (var roleid in input.RoleIds)
            {
                list.Add(new UserRole { UserId = input.UserId, RoleId = roleid });
            }

            return _userRoleRepository.InsertAsync(list);
        }



        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public Task UpdatePwd(UpdatePwdInput input)
        {
            // 获取用户Id
            var userId = long.Parse(App.User.FindFirst(ClaimConst.CLAINM_USERID).Value);
            var user = _userRepository.FindOrDefault(userId);
            if (!user.Password.Equals(MD5Encryption.Encrypt(input.OldPassword)))
            {
                throw Oops.Bah(ErrorCode.WrongOldPwd).StatusCode(ErrorStatus.ValidationFaild);
            }
            user.Password = MD5Encryption.Encrypt(input.Password);
            return _userRepository.UpdateIncludeAsync(user, new string[] { "Password" });
        }
        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        [SecurityDefine("employee")]
        public Task ResetPwd(long userid)
        {
            var user = _userRepository.FindOrDefault(userid);
            user.Password = MD5Encryption.Encrypt(CommonConst.DEFAULT_PASSWORD);
            return _userRepository.UpdateIncludeAsync(user, new string[] { "Password" });
        }
        #endregion

        #region 转发管理
        /// <summary>
        /// 新增客户
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public Task AddCustomer(AddCustomer input)
        {

            if (input.Id == 0)
            {
                var strCustomerName = _custRepository.Where(m => m.CustomerName == input.CustomerName).FirstOrDefault();
                if (strCustomerName != null)
                {
                    throw Oops.Oh(ErrorCode.WrongValidation, "该客户名称已存在").StatusCode(ErrorStatus.ValidationFaild);
                }
                Customer customer = input.Adapt<Customer>();
                customer.CustomerName = input.CustomerName;
                customer.CreateTime = DateTime.Now;
                return _custRepository.InsertAsync(customer);
            }
            else
            {
                var strCustomerName = _custRepository.Where(m => m.CustomerName == input.CustomerName && m.ID != input.Id).FirstOrDefault();
                if (strCustomerName != null)
                {
                    throw Oops.Oh(ErrorCode.WrongValidation, "该客户名称已存在").StatusCode(ErrorStatus.ValidationFaild);
                }
                Customer customer = input.Adapt<Customer>();
                customer.ID = input.Id;
                customer.CustomerName = input.CustomerName;
                customer.CreateTime = DateTime.Now;
                return _custRepository.UpdateIncludeAsync(customer, new string[] { "CustomerName" });
            }

        }
        /// <summary>
        /// 查询客户+设备
        /// </summary>
        /// <returns></returns>
        public List<EntityTree> GetCustomer()
        {
            // 查询客户表数据
            var entityC = _custRepository.AsQueryable();
            // 查询设备表数据
            var entityD = _repTranDevice.AsQueryable();

            // 客户表是树的根节点，设备表是子节点
            var tree = new List<EntityTree>();
            // 构建客户表的树形结构
            tree.AddRange(entityC.Select(a => new EntityTree
            {
                deptId = a.ID,
                parentId = 0,
                deptName = a.CustomerName,
                children = entityD.Where(b => b.CustomerID == a.ID).Select(b => new EntityTree
                {
                    deptId = 100000 + b.ID,
                    parentId = a.ID,
                    deptName = b.DeviceNo + b.DeviceName,
                    // 设置子节点为空，因为通常子节点也不会有子节点
                    children = new List<EntityTree>()
                }).ToList()
            }));

            return tree;
        }

        public class EntityTree
        {
            public int deptId { get; set; }
            public int parentId { get; set; }
            public string deptName { get; set; }
            public List<EntityTree> children { get; set; }
        }

        /// <summary>
        /// 查询设备列表
        /// </summary>
        public PagedList<TransDevice> TranDeviceListAll(TransDeviceDto input)
        {
            var infoALL = _repTranDevice.AsQueryable();
            var list = infoALL.Where(b => b.CustomerID == input.Id).ToPagedList(input.page, input.size).Adapt<PagedList<TransDevice>>();
            return list;
        }

        public PagedList<TransDevice> TranDeviceListOne(TransDeviceDto input)
        {
            var infoALL = _repTranDevice.AsQueryable();
            var list = infoALL.Where(b => b.ID == input.Id).ToPagedList(input.page, input.size).Adapt<PagedList<TransDevice>>();
            return list;
        }
        /// <summary>
        /// 删除配置列表
        /// </summary>
        public Task DeleteTranDevice(long id)
        {
            var entity = _repTranDevice.Where(m => m.ID == id).FirstOrDefault();
            return _repTranDevice.DeleteAsync(entity);
        }

        ///
        /// 协议管理
        ///
        public PagedList<AgreeMent> AgreeMentListAll(TransDeviceDto input)
        {
            var getagree = _agreeRepository.AsQueryable();
            var getagreefield = _agreefieldRepository.AsQueryable();
            List<AgreeMent> list = new List<AgreeMent>();
            list.AddRange(getagree.Select(a => new AgreeMent
            {
                ID = a.ID,
                AgreeMentName = a.AgreeMentName,
                AgreeType = a.AgreeType,
                Des = a.Des,
                agreementFieldTemplates = getagreefield.Where(b => b.AgreementName == a.AgreeMentName).Select(b => new AgreementFieldTemplate
                {
                    FieldName = b.FieldName,
                    FieldChineseName = b.FieldChineseName
                }).ToList()
            }));
            var newlist = list.AsQueryable();
            var info = newlist.ToPagedList(input.page, input.size).Adapt<PagedList<AgreeMent>>();
            return info;
        }
        /// <summary>
        /// 新增协议
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public Task AddAgreeMent(AddAgreeMent input)
        {

            if (input.Id == 0)
            {
                var strAgreeMent = _agreeRepository.Where(m => m.AgreeMentName == input.AgreeMentName).FirstOrDefault();
                if (strAgreeMent != null)
                {
                    throw Oops.Oh(ErrorCode.WrongValidation, "该协议名称已存在").StatusCode(ErrorStatus.ValidationFaild);
                }
                AgreeMent agree = input.Adapt<AgreeMent>();
                agree.AgreeMentName = input.AgreeMentName;
                agree.AgreeType = input.AgreeType;
                agree.Des = input.Des;
                agree.CreateTime = DateTime.Now;
                return _agreeRepository.InsertAsync(agree);
            }
            else
            {
                var strAgreeMent = _agreeRepository.Where(m => m.AgreeMentName == input.AgreeMentName && m.ID != input.Id).FirstOrDefault();
                if (strAgreeMent != null)
                {
                    throw Oops.Oh(ErrorCode.WrongValidation, "该协议名称已存在").StatusCode(ErrorStatus.ValidationFaild);
                }
                AgreeMent agree = input.Adapt<AgreeMent>();
                agree.ID = input.Id;
                agree.AgreeMentName = input.AgreeMentName;
                agree.AgreeType = input.AgreeType;
                agree.Des = input.Des;
                agree.CreateTime = DateTime.Now;
                return _agreeRepository.UpdateIncludeAsync(agree, new string[] { "AgreeMentName", "AgreeType", "Des" });
            }
        }
        /// <summary>
        /// 删除协议
        /// </summary>
        public Task DeleteAgreeMent(long id)
        {
            var entity = _agreeRepository.Where(m => m.ID == id).FirstOrDefault();
            return _agreeRepository.DeleteAsync(entity);
        }

        /// <summary>
        /// 查询协议-标准/非标准，树形结构二级菜单显示
        /// </summary>
        /// <returns></returns>
        public List<ArgeeTree> GetAgreeType()
        {
            // 查询客户表数据
            var entityA = _agreeRepository.AsQueryable().GroupBy(e => e.AgreeType).Select(g => g.FirstOrDefault()).ToList();
            var entityB = _agreeRepository.AsQueryable();
            // 查询设备表数据

            // 客户表是树的根节点，设备表是子节点
            var tree = new List<ArgeeTree>();
            // 构建客户表的树形结构
            tree.AddRange(entityA.Select(a => new ArgeeTree
            {
                value = a.AgreeType == "标准协议" ? 0 : 1,
                label = a.AgreeType,
                children = entityB.Where(b => b.AgreeType == a.AgreeType).Select(b => new ArgeeTrees
                {
                    value = b.ID,
                    label = b.AgreeMentName
                }).ToList()
            }));
            return tree;
        }
        public class ArgeeTree
        {
            public int value { get; set; }
            public string label { get; set; }
            public List<ArgeeTrees> children { get; set; }
        }
        public class ArgeeTrees
        {
            public int value { get; set; }
            public string label { get; set; }
        }
        /// <summary>
        /// 获取要素列表
        /// </summary>
        /// <returns></returns>
        public List<EssConfig> GetEssConfig()
        {
            var list = _essRepository.AsQueryable().Adapt<List<EssConfig>>();
            return list;
        }
        /// <summary>
        /// 获取协议动态字段
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public List<AgreementFieldTemplate> GetAgreeField(long id)
        {
            var entityA = _agreeRepository.AsQueryable().Where(a => a.ID == id).FirstOrDefault();
            var entityB = _agreefieldRepository.AsQueryable().Where(b => b.AgreementName == entityA.AgreeMentName);
            var list = entityB.Adapt<List<AgreementFieldTemplate>>();
            return list;
        }

        public Task SaveTranDevice(TransDevice input)
        {
            if (input.ID == 0)
            {
                string[] deviceNo = input.DeviceNo.Split(',');
                var entities = new List<TransDevice>();
                for (int i = 0; i < deviceNo.Length; i++)
                {
                    string[] deviceName = input.DeviceName.Split(',');
                    string[] externaldeviceNo = input.ExternalDeviceNo.Split(',');
                    TransDevice td = input.Adapt<TransDevice>();
                    td.DeviceNo = deviceNo[i];
                    td.DeviceName = deviceName[i];
                    td.ExternalDeviceNo = externaldeviceNo[i];
                    td.EssCode = input.EssCode;
                    td.ReportTime = DateTime.Now;
                    td.Reladdress = input.Reladdress;
                    td.Port = input.Port;
                    td.AgreeMentID = input.AgreeMentID;
                    td.AgreeExample = input.AgreeExample;
                    td.CustomerID = input.CustomerID;
                    td.Status = input.Status;
                    td.CreateTime = DateTime.Now;
                    td.Des = input.Des;
                    td.AgreeMent_Json = input.AgreeMent_Json;
                    td.AgreeMentValue = input.AgreeMentValue;
                    td.AgreeName = input.AgreeName;
                    entities.Add(td);
                }
                return _repTranDevice.InsertAsync(entities);
            }
            else
            {
                var strAgreeMent = _repTranDevice.Where(m => m.DeviceNo == input.DeviceNo && m.ID != input.ID).FirstOrDefault();
                if (strAgreeMent != null)
                {
                    throw Oops.Oh(ErrorCode.WrongValidation, "设备编号已存在").StatusCode(ErrorStatus.ValidationFaild);
                }
                TransDevice td = input.Adapt<TransDevice>();
                td.ID = input.ID;
                td.DeviceNo = input.DeviceNo;
                td.ExternalDeviceNo = input.ExternalDeviceNo;
                td.EssCode = input.EssCode;
                td.ReportTime = DateTime.Now;
                td.Reladdress = input.Reladdress;
                td.Port = input.Port;
                td.AgreeMentID = input.AgreeMentID;
                td.AgreeExample = input.AgreeExample;
                td.Status = input.Status;
                td.Des = input.Des;
                td.AgreeMent_Json = input.AgreeMent_Json;
                td.AgreeMentValue = input.AgreeMentValue;
                td.AgreeName = input.AgreeName;
                td.CreateTime = DateTime.Now;
                return _repTranDevice.UpdateIncludeAsync(td, new string[] { "DeviceNo", "ExternalDeviceNo", "EssCode", "ReportTime", "Reladdress", "Port",
                    "AgreeMentID", "AgreeExample", "Status", "Des", "AgreeMent_Json", "AgreeMentValue", "AgreeName", "CreateTime" });
            }
        }

        /// <summary>
        /// 删除客户
        /// </summary>
        public Task DeleteCustomer(long id)
        {
            var entity = _custRepository.Where(m => m.ID == id).FirstOrDefault();
            return _custRepository.DeleteAsync(entity);
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="file"></param>
        /// <param name="customField"></param>
        /// <returns></returns>
        public async Task<string> Upload(IFormFile file, [FromForm] int customField)
        {
            var strAgreeMent = _fileRepository.Where(m => m.FileName == file.FileName && m.CustomerID == customField).FirstOrDefault();
            if (strAgreeMent != null)
            {
                throw Oops.Oh(ErrorCode.WrongValidation, "文件已存在,请勿重复上传").StatusCode(ErrorStatus.ValidationFaild);
            }

            var filePath = Path.Combine(Directory.GetCurrentDirectory(), "uploads", $"{file.FileName}");

            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }
            // 保存文件信息到数据库
            FileCustomer list = customField.Adapt<FileCustomer>();
            list.CustomerID = customField;
            list.FileName = file.FileName;
            list.FileAddress = "http://localhost:9002/" + file.FileName;
            list.CreateTime = DateTime.Now;
            await _fileRepository.InsertAsync(list);

            return "上传成功";
        }
        /// <summary>
        /// 上传文件-公共协议文档
        /// </summary>
        /// <param name="file"></param>
        /// <param name="customField"></param>
        /// <returns></returns>
        public async Task<string> UploadAgree(IFormFile file, [FromForm] int customField, [FromForm] string selectAgreeName, [FromForm] string selectAgreeType)
        {
            var strAgreeMent = _fileRepository.Where(m => m.FileName == selectAgreeName + "_" + selectAgreeType + "文档" + Path.GetExtension(file.FileName) && m.CustomerID == customField).FirstOrDefault();
            if (strAgreeMent != null)
            {
                throw Oops.Oh(ErrorCode.WrongValidation, "文件已存在,请勿重复上传").StatusCode(ErrorStatus.ValidationFaild);
            }
            var filePath = Path.Combine(Directory.GetCurrentDirectory(), "uploads", selectAgreeName +"_"+ selectAgreeType + "文档"+ Path.GetExtension(file.FileName));

            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }
            // 保存文件信息到数据库
            FileCustomer list = customField.Adapt<FileCustomer>();
            list.CustomerID = customField;
            list.FileName = selectAgreeName + "_" + selectAgreeType + "文档" + Path.GetExtension(file.FileName);
            list.FileAddress = "http://localhost:9002/" + selectAgreeName + "_" + selectAgreeType + "文档" + Path.GetExtension(file.FileName);
            list.CreateTime = DateTime.Now;
            await _fileRepository.InsertAsync(list);

            return "上传成功";
        }
        /// <summary>
        /// 上传字段文件
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public async Task<string> UploadField(IFormFile file)
        {
            var filePath = Path.Combine("D:", "DB", $"{file.FileName}");
            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }
            return "上传成功";
        }
        
        public List<FileCustomer> GetFileMange(long id)
        {
            var list = _fileRepository.AsQueryable().Where(a => a.CustomerID == id).Adapt<List<FileCustomer>>();
            return list;
        }

        /// <summary>
        /// 状态信息，协议-设备情况
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public PagedList<TransDevice> AgreeInfoListAll(TransDeviceDto input)
        {
            var getagree = _repTranDevice.AsQueryable().Where(a => a.CustomerID == 99999999);
            var info = getagree.ToPagedList(input.page, input.size).Adapt<PagedList<TransDevice>>();
            return info;
        }
        /// <summary>
        /// 删除客户对应文档
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Task DeleteFile(long id)
        {
            var entity = _fileRepository.Where(m => m.ID == id).FirstOrDefault();
            return _fileRepository.DeleteAsync(entity);
        }
        #endregion

        #region  mysql 请求设备号

        /// <summary>
        /// 获取设备号列表
        /// </summary>
        /// <returns></returns>
        public PagedList<device_info> ListDeviceNo(DeviceInfoDto input)
        {
            var entityA = _DeviceNoClassRepository.AsQueryable().ToList();
            var entityB = _repTranDevice.AsQueryable().ToList();
            var list = entityA.Where(a => !entityB.Any(b => b.DeviceNo == a.ST)).ToList();
            var newlist = list.AsQueryable();
            if (!string.IsNullOrEmpty(input.DeviceSeachName))
            {
                newlist = newlist.Where(m => m.ST.Contains(input.DeviceSeachName) || m.NAME.Contains(input.DeviceSeachName));
            }
            return newlist.ToPagedList(input.page, input.size).Adapt<PagedList<device_info>>();
        }
        /// <summary>
        /// 获取所有协议下拉框展示
        /// </summary>
        /// <returns></returns>
        public List<AgreeMent> GetSelectAgree()
        {
            var getagree = _agreeRepository.AsQueryable().Adapt<List<AgreeMent>>();
            return getagree;
        }
        #endregion
    }
}